<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="积分商品" prop="integralProName">
        <el-input
          v-model="queryParams.integralProName"
          placeholder="请输入积分商品"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否上架" prop="ifFlag">
        <el-select v-model="queryParams.ifFlag" placeholder="选择上架状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.product_flag"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['projects:SlIntegralPro:add']"
        >新增商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['projects:SlIntegralPro:remove']"
        >删除商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['projects:SlIntegralPro:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="SlIntegralProList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="积分商品" align="center" prop="integralProName" />
      <el-table-column label="积分商品封面图" align="center" prop="integralProImg" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.integralProImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="积分值" align="center" prop="integralProIntegral" />
      <el-table-column label="现金" align="center" prop="integralProMoney" />
      <el-table-column label="原价" align="center" prop="integralProOldMoney" />
      <el-table-column label="商品说明" align="center" prop="integralProText" />
      <el-table-column label="是否上架" align="center" prop="ifFlag">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.product_flag" :value="scope.row.ifFlag"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['projects:SlIntegralPro:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['projects:SlIntegralPro:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改积分产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 第一行：积分商品和是否上架 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="积分商品" prop="integralProName">
              <el-input v-model="form.integralProName" placeholder="请输入积分商品" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否上架" prop="ifFlag">
              <el-radio-group v-model="form.ifFlag">
                <el-radio
                  v-for="dict in dict.type.product_flag"
                  :key="dict.value"
                  :label="parseInt(dict.value)"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第二行：积分值和现金 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="积分值" prop="integralProIntegral">
              <el-input v-model.number="form.integralProIntegral" placeholder="请输入积分值" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现金" prop="integralProMoney">
              <el-input v-model.number="form.integralProMoney" placeholder="请输入现金" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第三行：原价 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="integralProOldMoney">
              <el-input v-model.number="form.integralProOldMoney" placeholder="请输入原价" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 第四行：商品说明（文本域） -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品说明" prop="integralProText">
              <el-input 
                v-model="form.integralProText" 
                placeholder="请输入商品说明" 
                type="textarea" 
                rows="4"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 最后：封面图上传 -->
        <el-form-item label="封面图" prop="integralProImg">
          <!-- 使用v-loading指令替代el-loading组件 -->
          <div v-loading="uploadLoading" element-loading-text="上传中...">
            <el-upload 
              ref="upload" 
              :file-list="fileList" 
              :action="uploadUrl" 
              :headers="headers"
              :auto-upload="true" 
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-remove="handleRemove"
              :on-error="handleUploadError"
              list-type="picture-card"
              accept="image/jpeg,image/png,image/jpg"
              :limit="1"
              name="file">
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">
                支持上传 JPG/PNG 格式图片，不超过 2MB，仅可上传一张
              </div>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSlIntegralPro, getSlIntegralPro, delSlIntegralPro, addSlIntegralPro, updateSlIntegralPro } from "@/api/projects/SlIntegralPro";
import { getToken } from "@/utils/auth";

export default {
  name: "SlIntegralPro",
  dicts:['product_flag'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 积分产品表格数据
      SlIntegralProList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        integralProName: null,
        ifFlag: null,
      },
      // 表单参数
      form: {
        integralProImg: "" // 初始化空字符串而非null
      },
      // 表单校验
      rules: {
        integralProName: [
          { required: true, message: "积分商品不能为空", trigger: "blur" }
        ],
        integralProIntegral: [
          { required: true, type: "number", message: "积分值不能为空", trigger: "blur" }
        ],
        integralProMoney: [
          { required: true, type: "number", message: "现金不能为空", trigger: "blur" }
        ],
        integralProOldMoney: [
          { required: true, type: "number", message: "原价不能为空", trigger: "blur" }
        ],
        integralProImg: [
          { 
            required: true, 
            validator: function(rule, value, callback) {
              // 自定义验证器：检查表单字段或文件列表
              if (!value && this.fileList.length === 0) {
                callback(new Error("请上传封面图"));
              } else {
                callback();
              }
            }.bind(this),
            trigger: ["change", "blur"]
          }
        ],
        ifFlag: [
          { required: true, message: "请选择是否上架", trigger: "change" }
        ]
      },
      // 图片上传相关
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      headers: {
        Authorization: "Bearer " + getToken()
      },
      fileList: [],
      uploadLoading: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询积分产品列表 */
    getList() {
      this.loading = true;
      listSlIntegralPro(this.queryParams).then(response => {
        this.SlIntegralProList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        integralProName: null,
        integralProImg: "",
        integralProIntegral: null,
        integralProMoney: null,
        integralProOldMoney: null,
        integralProText: null,
        ifFlag: null
      };
      this.fileList = [];
      this.uploadLoading = false;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加积分产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSlIntegralPro(id).then(response => {
        this.form = response.data;
        // 处理图片回显
        if (this.form.integralProImg) {
          this.fileList = [{
            name: `image-${Date.now()}`,
            url: this.form.integralProImg
          }];
        }
        this.open = true;
        this.title = "修改积分产品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理图片数据
          this.form.integralProImg = this.fileList.length > 0 ? this.fileList[0].url : "";
          
          if (this.form.id != null) {
            updateSlIntegralPro(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSlIntegralPro(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除积分产品编号为"' + ids + '"的数据项？').then(function() {
        return delSlIntegralPro(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('projects/SlIntegralPro/export', {
        ...this.queryParams
      }, `SlIntegralPro_${new Date().getTime()}.xlsx`)
    },
    /** 图片上传前校验 */
    beforeUpload(file) {
      // 显示上传中状态
      this.uploadLoading = true;
      
      // 校验文件大小
      const isLt2MB = file.size / 1024 / 1024 <= 2;
      if (!isLt2MB) {
        this.$message.error('上传图片大小不能超过 2MB!');
        this.uploadLoading = false;
        return false;
      }
      
      // 校验文件格式
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      if (!isImage) {
        this.$message.error('请上传 JPG/PNG 格式的图片!');
        this.uploadLoading = false;
        return false;
      }
      
      return true;
    },
    /** 图片上传成功处理 */
    handleUploadSuccess(response, file, fileList) {
      this.uploadLoading = false;
      if (response.code === 200) {
        // 替换为服务器返回的URL
        file.url = response.url;
        this.fileList = fileList;
        // 同步更新表单字段
        this.form.integralProImg = response.url;
        // 手动触发表单验证
        this.$refs.form.validateField('integralProImg');
        this.$message.success('图片上传成功');
      } else {
        this.handleUploadError(response, file);
      }
    },
    /** 图片上传失败处理 */
    handleUploadError(response, file) {
      this.uploadLoading = false;
      // 清空表单图片字段
      this.form.integralProImg = "";
      this.$message.error(response.msg || '图片上传失败，请重试');
      // 从文件列表中移除失败的文件
      this.fileList = this.fileList.filter(f => f.uid !== file.uid);
      // 手动触发表单验证
      this.$refs.form.validateField('integralProImg');
    },
    /** 移除图片处理 */
    handleRemove(file, fileList) {
      this.fileList = fileList;
      // 更新表单中的图片数据
      this.form.integralProImg = fileList.length > 0 ? fileList[0].url : "";
      // 手动触发表单验证
      this.$refs.form.validateField('integralProImg');
    }
  }
};
</script>
